package com.league.blog.system.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 黄豪琦
 * 日期:2019-07-05 13:28
 * 说明:
 */
@Component
public class RedisUtils {

    private RedisTemplate<String, Object> template;

    @Autowired
    public void setTemplate(RedisTemplate<String, Object> template) {
        this.template = template;
    }

    //添加 获取

    /**
     * 获取普通缓存
     * @param key
     * @return
     */
    public Object get(String key){
        return key == null ? null : template.opsForValue().get(key);
    }

    public boolean put(String key, Object obj){
        try {
            template.opsForValue().set(key, obj);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 添加普通缓存
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean put(String key, Object value, long time){
        try {
            if(time > 0){
                template.opsForValue().set(key, value, time);
                return true;
            } else {
                template.opsForValue().set(key, value);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取某个list中所有的值
     * @param key
     * @return
     */
    public List<Object> getList(String key){
        try {
            return template.opsForList().range(key, 0, -1);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 存一个list
     * @param key 键
     * @param value 值
     * @return false失败
     */
    public boolean putList(String key, Object value){
        try {

            template.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean delete(String key){
        return template.delete(key);
    }
}
